﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wuther.Bussiness.Interface;
using Wuther.Entities.Models;
using Wuther.Util.DtoParameters;
using Wuther.Util.Helper;
using Wuther.Util.Models;
using Wuther.Util.PropertyMapping;

namespace Wuther.Bussiness.Service
{
    public class BlogCommentRepository : Repository<BlogComment>, IBlogCommentRepository
    {
        private readonly DbContext _context;
        private readonly IPropertyMappingService _propertyMappingService;
        public BlogCommentRepository(DbContext context, IPropertyMappingService propertyMappingService) : base(context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _propertyMappingService = propertyMappingService ?? throw new ArgumentNullException(nameof(propertyMappingService));
        }

        public async Task<BlogComment> GetBlogCommentAsync(int id)
        {
            var blogComment = await _context.FindAsync<BlogComment>(id);
            return blogComment;
        }

        public async Task<PagedList<BlogComment>> GetBlogCommentsAsync(DtoBlogCommentParameter parameter)
        {
            IQueryable<BlogComment> queryExpression = _context.Set<BlogComment>();

            if (parameter.BlogId != null && parameter.BlogId.Value != 0)
            {
                queryExpression = queryExpression.Where(c => c.BlogId == parameter.BlogId);
            }
            if (!string.IsNullOrWhiteSpace(parameter.BlogFlag))
            {
                queryExpression = queryExpression.Where(c => c.BlogFlag.Contains(parameter.BlogFlag));
            }
            if (!string.IsNullOrWhiteSpace(parameter.BlogPath))
            {
                queryExpression = queryExpression.Where(c => c.BlogPath.Contains(parameter.BlogPath));
            }
            if (!string.IsNullOrWhiteSpace(parameter.UserAccount))
            {
                queryExpression = queryExpression.Where(c => c.UserAccount == parameter.UserAccount);
            }

            var mappingDictionary = _propertyMappingService.GetPropertyMapping<BlogCommentDto, BlogComment>();
            queryExpression = queryExpression.ApplySort(parameter.OrderBy, mappingDictionary);
            return await PagedList<BlogComment>.CreateAsync(queryExpression, parameter.PageNumber, parameter.PageSize);
        }
    }
}
